package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.WxReceiveBO;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.bean.WxBaseData;
import com.cskaoyan.bean.bo.WxCouponBO;
import com.cskaoyan.mapper.MallCartMapper;
import com.cskaoyan.mapper.MallCouponMapper;
import com.cskaoyan.mapper.MallCouponUserMapper;
import com.cskaoyan.service.WxCouponService;
import com.cskaoyan.util.WxMyPageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: Chunlai
 * @description:
 * @time: 2021/7/11 22:23
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {

    @Autowired
    MallCouponUserMapper mallCouponUserMapper;

    @Autowired
    MallCouponMapper mallCouponMapper;

    @Autowired
    MallCartMapper mallCartMapper;

    @Override
    public WxBaseData selectCouponInfos(WxCouponBO wxCouponBO) { //todo 检查完这个接口

        Subject subject = SecurityUtils.getSubject();
        MallUser mallUser = (MallUser) subject.getPrincipal();
        Integer nameid = mallUser.getId();

        WxMyPageHelper.startPage(wxCouponBO);


        // 获取未使用的优惠券，排除了过期的和已经用过的
        List<Integer> nameIdList = mallCouponUserMapper.selectbynameId(nameid);
        Date date = new Date();
        for (Integer id : nameIdList) {
            //获得优惠券的
            MallCoupon mallCoupon = mallCouponMapper.selectByPrimaryKey(id);
            Date endTime = mallCoupon.getEndTime();
            long endtime =  endTime.getTime();
            long nowtime =  date.getTime();
            long differ =  endtime - nowtime;
            if (differ <= 0){ // 说明优惠券过期了或者正在过期
                mallCouponUserMapper.updatestatusById(nameid,id);
            }
        }

        MallCouponUserExample mallCouponUserExample = new MallCouponUserExample();
        MallCouponUserExample.Criteria criteria = mallCouponUserExample.createCriteria();
//        todo criteria.andUserIdEqualTo() , 获取用户的id信息
        criteria.andUserIdEqualTo(nameid);
        criteria.andStatusEqualTo(wxCouponBO.getStatus());
        List<MallCouponUser> mallCouponUserList = mallCouponUserMapper.selectByExample(mallCouponUserExample);

        PageInfo<MallCouponUser> mallCouponUserPageInfo = new PageInfo<>(mallCouponUserList);
        int size = mallCouponUserPageInfo.getSize();

        ArrayList<MallCoupon> mallCoupons = new ArrayList<>();
        for (MallCouponUser mallCouponUser : mallCouponUserList) {
            Integer couponId = mallCouponUser.getCouponId();
            MallCoupon mallCoupon = mallCouponMapper.selectByPrimaryKey(couponId);
            mallCoupons.add(mallCoupon);
        }
        return WxBaseData.ok(mallCoupons,size);
    }


    @Override
    public WxBaseData selectCouponUnUsed(WxCouponBO wxCouponBO) {
        //todo 未登录做处理
        WxMyPageHelper.startPage(wxCouponBO);
        Subject subject = SecurityUtils.getSubject();
        MallUser mallUser = (MallUser) subject.getPrincipal();
        List<MallCoupon> mallCouponList = null;
        if (mallUser != null){
            Integer id = mallUser.getId();
            List<Integer> userids = mallCouponUserMapper.selectCouponId(id);    // 拿到用户的id 下的 coupon_id : 用户的所有优惠券
            //todo 用来筛选一个用户可以领取多个的优惠券，并且优惠券(个数)仍存在的
            // todo -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --
            // userids 这个list 里面存储了你拥有的所有优惠券，包括没用的和过期的...
            // 我们要把我们每个优惠券的限制拿到，并且查看自己已经有多少个了，如果自己还可以领，并且你这个优惠券数量还有，我们从userids中删除该优惠券id

            List<Integer> useridss = mallCouponUserMapper.selectCouponId(id);

            for (Integer couponid : userids) {
                CouponpartInfoVO couponpartInfoVO = mallCouponMapper.getLimitandtotalandstatus(couponid);
                int index = mallCouponUserMapper.selectcountidbyId(couponid);
                if (couponpartInfoVO.getStatus() ==  0 && couponpartInfoVO.getLimit() > 1 && couponpartInfoVO.getTotal() >= 0 && index < couponpartInfoVO.getLimit() ){
                    //我这个优惠券现在是有可用的，你可以领取多张的，你也有多个的
                    useridss.remove(couponid);
                }
            }
            // todo -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --  -- --
            List<MallCoupon> mallCouponListsss = new ArrayList<>();
            List<MallCoupon> mallCouponLists = mallCouponMapper.selectByUserCouponUnUsedId(useridss); // 查到优惠券的信息，用户没有拿到的
            // todo 这里面的list并没有排除个数不够的和状态为过期的
            for (MallCoupon mallCoupon : mallCouponLists) {
                if (mallCoupon.getTotal()>=0 && mallCoupon.getStatus() == 0){//才会添加
                    mallCouponListsss.add(mallCoupon);
                }
            }
            mallCouponList = mallCouponListsss;
        }else {//用户没有登录,显示全部的优惠券
            mallCouponList = mallCouponMapper.selectCouponUnlogin(); // 查到优惠券的信息，用户没有拿到的
        }
        List<WxTimetTypeVO> wxTimetTypeVOList = new ArrayList<>();
        if (mallCouponList.size() > 0){
            for (MallCoupon mallCoupon : mallCouponList) {
                WxTimetTypeVO wxTimetTypeVO = null;
                if (mallCoupon.getTimeType() == 1){ // 开始时间 - 结束时间
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String format1 = formatter.format(mallCoupon.getStartTime());
                    String format2 = formatter.format(mallCoupon.getEndTime());
                    wxTimetTypeVO = new WxTimeFromToVO(mallCoupon.getId(),mallCoupon.getName(),mallCoupon.getDesc(),mallCoupon.getTag(),mallCoupon.getDiscount().doubleValue(),mallCoupon.getMin().doubleValue(),mallCoupon.getDays(),format1,format2);
                }
                if (mallCoupon.getTimeType() == 0 ){// 天数
                    wxTimetTypeVO = new WxTimetTypeVO(mallCoupon.getId(),mallCoupon.getName(),mallCoupon.getDesc(),mallCoupon.getTag(),mallCoupon.getDiscount().doubleValue(),mallCoupon.getMin().doubleValue(),mallCoupon.getDays());
                }
                wxTimetTypeVOList.add(wxTimetTypeVO);
            }
        }
        PageInfo<WxTimetTypeVO> mallCouponUserPageInfo = new PageInfo<>(wxTimetTypeVOList);
        int size = mallCouponUserPageInfo.getSize();
        return WxBaseData.ok(wxTimetTypeVOList,size);
    }


    public WxBaseData selectCouponUnUsed1(WxCouponBO wxCouponBO) {
        WxMyPageHelper.startPage(wxCouponBO);

        List<Integer> selectCouponId = mallCouponMapper.selectCouponId();

        List<Integer> selectByUserCouponUnUsedId = mallCouponUserMapper.selectByUserCouponUnUsedId(selectCouponId);
        List<MallCoupon> mallCouponList = new ArrayList<>();
        for (Integer integer : selectByUserCouponUnUsedId) {
            MallCoupon mallCoupon = mallCouponMapper.selectByPrimaryKey(integer);
            mallCouponList.add(mallCoupon);
        }

        PageInfo<MallCoupon> mallCouponUserPageInfo = new PageInfo<>(mallCouponList);
        int size = mallCouponUserPageInfo.getSize();

        return WxBaseData.ok(selectByUserCouponUnUsedId,size);
    }

    @Override
    public int insertCouponById(ExchangeCode exchangeCode) {
        //todo  模拟的用户id
        Subject subject = SecurityUtils.getSubject();
        MallUser mallUser = (MallUser) subject.getPrincipal();
        Integer userid = mallUser.getId();

        String code = exchangeCode.getCode();
        int index = mallCouponMapper.selectCountId(code);
        if (index == 0 ){// 说明这个优惠码不存在
            return 404;
        }
        if (index == 1){ // 说明这个优惠码存在
            MallCoupon mallCoupon = mallCouponMapper.selectbyCode(code);
            int mount = mallCouponUserMapper.selectcountbyId(mallCoupon.getId());
            if (mount == 1){//说明该用户有一张这个优惠券了
                int limit = mallCoupon.getLimit();
                if (limit == 1){ //限制领取一张
                    return 101;
                }else {
                    //我们要扣除优惠券的一个数量
                    Integer id = mallCoupon.getId();
                    int amount = mallCouponMapper.selecttotalbyId(id);
                    if (amount > 0){
                        amount = amount - 1 ;
                        mallCouponMapper.updatetotalById(id ,amount);
                    }
                    //同时为用户添加这个优惠券
                    MallCouponUser mallCouponUser = new MallCouponUser(null,userid,mallCoupon.getId(),(short)0,null,mallCoupon.getStartTime(),mallCoupon.getEndTime(),0,new Date(),new Date(),false);
                    mallCouponUserMapper.insertSelective(mallCouponUser);
                    return 200; //拿到优惠券
                }
            }
            if (mount == 0){//说明该用户没有这个优惠券
                //我们要扣除优惠券的一个数量
                Integer id = mallCoupon.getId();
                int amount = mallCouponMapper.selecttotalbyId(id);
                if (amount > 0){
                    amount = amount - 1 ;
                    mallCouponMapper.updatetotalById(id ,amount);
                }
                //同时为用户添加这个优惠券
                MallCouponUser mallCouponUser = new MallCouponUser(null,userid,mallCoupon.getId(),(short)0,null,mallCoupon.getStartTime(),mallCoupon.getEndTime(),0,new Date(),new Date(),false);
                mallCouponUserMapper.insertSelective(mallCouponUser);
                return 200; //拿到优惠券
            }
            if (mount > 1 && mallCoupon.getLimit()> mount){//说明该用户有多张这个优惠券了
                //我们要扣除优惠券的一个数量
                Integer id = mallCoupon.getId();
                int amount = mallCouponMapper.selecttotalbyId(id);
                if (amount > 0){
                    amount = amount - 1 ;
                    mallCouponMapper.updatetotalById(id ,amount);
                }
                //同时为用户添加这个优惠券
                MallCouponUser mallCouponUser = new MallCouponUser(null,userid,mallCoupon.getId(),(short)0,null,mallCoupon.getStartTime(),mallCoupon.getEndTime(),0,new Date(),new Date(),false);
                mallCouponUserMapper.insertSelective(mallCouponUser);
                return 200; //拿到优惠券
            }
        }

//        StartandEndTimeVO startandEndTimeVO = mallCouponMapper.selectStartandEndTime(e);
//        MallCouponUser mallCouponUser = new MallCouponUser();
//        mallCouponUserMapper
        return 101;
    }

    @Override
    public int insertReceiveById(WxReceiveBO wxReceiveBO) {
        //todo
        Subject subject = SecurityUtils.getSubject();
        MallUser mallUser = (MallUser) subject.getPrincipal();
        Integer nameid = mallUser.getId();

        int couponId = wxReceiveBO.getCouponId();

        int index = mallCouponUserMapper.selectCountByCouponId(couponId , nameid); // 我现有这个优惠券的个数

        MallCoupon mallCoupon = mallCouponMapper.selectbyCouponId(couponId);

        int limit = mallCoupon.getLimit();          //限制领取个数
        Integer total = mallCoupon.getTotal();      //优惠券剩下多少

        if (index == 0){//我现在没有这个优惠券
            MallCouponUser mallCouponUser = new MallCouponUser(null,nameid,couponId,(short)0,null,mallCoupon.getStartTime(),mallCoupon.getEndTime(),0,new Date(),new Date(),false);
            mallCouponUserMapper.insertSelective(mallCouponUser);
            //给该用户添加优惠券
            //优惠券数量 - 1
            if (total > 0 ) {
                total = total - 1;
                if (total == 0){
                    total = -1;
                }
                mallCouponMapper.updatetotalById(couponId,total);
            }
            return 200;
        }
        if (index == 1 && limit == 1 ){//我现在有一个这个优惠券，并且限制我领取一个
            return 101;
        }

        if (index > 0 && index < limit){//我有多个这个优惠券，我还可以进行添加
            MallCouponUser mallCouponUser = new MallCouponUser(null,nameid,couponId,(short)0,null,mallCoupon.getStartTime(),mallCoupon.getEndTime(),0,new Date(),new Date(),false);
            mallCouponUserMapper.insertSelective(mallCouponUser);
            //给该用户添加优惠券
            //优惠券数量 - 1
            if (total != 0) {
                total = total - 1;
                mallCouponMapper.updatetotalById(couponId,total);
            }
            return 200;
        }
        if (index > 0 && index >= limit) {//我有多个这个优惠券，我还可以进行添加
            return 101;
        }
        return 200;
    }

    @Override
    public List<WxCouponList> selectlist(Integer mallCoupon) {
        double price = 0 ;

        Subject subject = SecurityUtils.getSubject();
        MallUser mallUser = (MallUser) subject.getPrincipal();
        Integer nameid = mallUser.getId();

        // todo 获取购物车或者直接下单所需要的金额
        if (mallCoupon == 0 ){ // 说明获取了购物车的全部的商品
            MallCartExample mallCartExample = new MallCartExample();
            MallCartExample.Criteria criteria = mallCartExample.createCriteria();
            criteria.andUserIdEqualTo(nameid);
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);

            List<MallCart> mallCarts = mallCartMapper.selectByExample(mallCartExample);
            for (MallCart mallCart : mallCarts) {
                double price_temp = mallCart.getPrice().doubleValue();
                int number = mallCart.getNumber();
                double price_temps = price_temp * number;
                price += price_temps;
            }

        }else {
            MallCart mallCart = mallCartMapper.selectByPrimaryKey(mallCoupon);
            int number = mallCart.getNumber();
            price = mallCart.getPrice().doubleValue() * number;
        }

        // todo 筛选优惠券
        MallCouponUserExample mallCouponUserExample = new MallCouponUserExample();
        MallCouponUserExample.Criteria criteria = mallCouponUserExample.createCriteria();

        criteria.andUserIdEqualTo(nameid);
        criteria.andStatusEqualTo(0);
        criteria.andDeletedEqualTo(false);
        //获取用户可以使用的优惠券
        List<MallCouponUser> mallCouponUserList = mallCouponUserMapper.selectByExample(mallCouponUserExample);

        ArrayList<WxCouponList> wxCouponLists = new ArrayList<>();

        //说明用户没有拿到优惠券
        if (mallCouponUserList.size() == 0){
            return wxCouponLists;
        }else {//说明用户有优惠券
            for (MallCouponUser mallCouponUser : mallCouponUserList) {
                // todo 获取到了优惠券的id
                Integer couponId = mallCouponUser.getCouponId();
                MallCoupon mallCoupon1 = mallCouponMapper.selectByPrimaryKey(couponId);
                double min = mallCoupon1.getMin().doubleValue();
                if (price >= min){
                    WxCouponList wxCouponList = new WxCouponList(mallCoupon1.getId(),mallCoupon1.getName(),mallCoupon1.getDesc(),mallCoupon1.getTag(),mallCoupon1.getMin().toString(),mallCoupon1.getDiscount().toString(),mallCoupon1.getStartTime().toString(),mallCoupon1.getEndTime().toString());
                    wxCouponLists.add(wxCouponList);
                }
            }
            wxCouponLists.sort(new Comparator<WxCouponList>() {
                @Override
                public int compare(WxCouponList o1, WxCouponList o2) {
                    return o1.getMin().compareTo(o2.getMin());
                }
            });
            return wxCouponLists;
        }
    }

}